<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="success"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="addemluser"
            :disabled="!checkPremission('add-user')"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column prop="staffPhoto" label="头像" width="120px">
            <template slot-scope="{ row }">
              <img
                style="width: 80px; height:80px;"
                v-imgerror="defaultImg"
                :src="row.staffPhoto"
                alt=""
                @click="btnCanvas(row.staffPhoto)"
                class="titleImg"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="手机号"
            prop="mobile"
            width="120px"
          ></el-table-column>
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployee"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch v-model="row.enableState"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="assignClick(row.id)"
                :disabled="!checkPremission('set-user')"
                >角色</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="delemp(row.id)"
                :disabled="!checkPremission('del-user')"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          >
          </el-pagination>
        </el-row>
      </el-card>
      <add-employees :showDialog.sync="showDialog" />
      <el-dialog title="二维码" :visible="shower" @close="shower = false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas"></canvas>
        </el-row>
      </el-dialog>
    </div>

    <!-- 角色弹层 -->
    <assign-role
      :showRoleDialog.sync="showRoleDialog"
      :userId="userId"
      ref="assignRole"
    />
  </div>
</template>

<script>
import { getempList, delemp } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees' // 引入员工的枚举对象
import addEmployees from './components/add-employees.vue'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
import qrCode from 'qrcode'

export default {
  data () {
    return {
      defaultImg: require('@/assets/common/head.jpg'),
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      loading: false,
      showDialog: false,
      showRoleDialog: false, // 显示分配角色弹层
      userId: null,
      shower: false //二维码弹层
    }
  },
  components: {
    addEmployees,
    AssignRole
  },
  created () {
    this.getempList()
  },
  methods: {
    // 二维码弹层
    btnCanvas (url) {
      // url: 图片
      if (url) {
        this.shower = true
        this.$nextTick(() => {
          qrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 获取员工列表
    async getempList () {
      this.loading = true
      let res = await getempList(this.page)
      this.page.total = res.data.total
      this.list = res.data.rows
      this.loading = false
      // console.log(res)
      this.list.forEach(item => {
        item.enableState = item.enableState == 1 ? true : false
      })
    },
    changePage (newpage) {
      this.page.page = newpage
      this.getempList()
    },
    // 格式化聘用形式
    formatEmployee (row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '非正式'
    },
    assignClick (id) {
      console.log(id)
      this.userId = id
      // console.log(this.$refs.assignRole)
      this.$refs.assignRole.userProfile(id)
      this.showRoleDialog = true
    },
    // 删除员工
    async delemp (id) {
      console.log(id)
      try {
        await this.$confirm('确认删除该员工吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        await delemp(id)
        // 判断如果只有一条数据就要加载上一页,单时还是要保证不是第一页
        if (this.list.length == 1 && this.page.page != 1) {
          this.page.page--
        }
        this.$message.success('删除成功')
        this.getempList() // 重新拉去数据
      } catch (error) {
        console.log(error)
      }
    },
    // 新增员工
    addemluser () {
      this.showDialog = true
    },
    // excel导出
    exportData () {
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getempList({ page: 1, size: this.page.total })
        console.log(res)
        let rows = res.data.rows
        const data = this.formtJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data
        })
      })
    },
    // 表头数据和数据进行对应
    formtJson (headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          // 需要判断字段
          if (
            headers[key] === 'timeOfEntry' ||
            headers[key] === 'correctionTime'
          ) {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(
              obj => obj.id === item[headers[key]]
            )
            return obj ? obj.value : '非正式'
          }
          return item[headers[key]]
        })
      })
    }
  }
}
</script>

<style>
.titleImg {
  border-radius: 50%;
}
</style>
